package com.example.netty.netty.TCPExample;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.ConcurrentHashMap;

@ChannelHandler.Sharable
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //通道准备好时触发
        ctx.channel().writeAndFlush(Unpooled.copiedBuffer("hello,server...", CharsetUtil.UTF_8));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //有读取事件时触发
        System.out.println(
                "===接受到信息：" + ((ByteBuf) msg).toString(CharsetUtil.UTF_8)
                        + ",服务器地址：" + ctx.channel().remoteAddress()
                        + ",eventLoopHashCode:" + Thread.currentThread().hashCode()
                        + ",channelHashCode:" + ctx.channel().hashCode()
                        + "上下文信息："+ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
